<script lang="ts" setup>
import HomeRequest from '@/request/homeRequest';
import { useAppStore, useControllerStore } from '@/store';
import { navigate } from '@/utils/navigate';
import to from '@/utils/to';
import CompPriceDiffPopup from '@/pages/home/component/CompPriceDiffPopup.vue';
import useToast from '@/hooks/useToast';

interface IState {
  activityList: IObtainActivityList[];
  show: boolean;
  columns: IObtainActivityButtonListRes[];
  selectAactivity?: IObtainActivityList;
}

const store = useAppStore();
const { showToast } = useToast();
const state = reactive<IState>({ activityList: [], show: false, columns: [] });

onLoad(() => {
  fetchObtainActivityList();
});

// 请求活动列表
const fetchObtainActivityList = () => {
  const params = { pageNo: 1, pageSize: 1000, beeperId: store.$state.beeperId, secondClassifyIds: store.$state.btnInformation!.classifyIds.toString() };
  HomeRequest.ObtainActivityList({ ...params, hasLoading: true }).then((res) => {
    state.activityList = res.data.list;
  });
};

// 活动产品点击
const handleActivityProductClick = async (data: IObtainActivityList) => {
  const [err, res] = await to(HomeRequest.ObtainActivityButtonList({ activityId: data.activityId }));
  if (err) return;
  state.selectAactivity = data;
  state.columns = res.data;
  state.show = true;
};

// 产品活动选中事件处理
const handleActivityProductConfirm = async (selected: IObtainActivityButtonListRes) => {
  const [err, res] = await to(HomeRequest.ObtainProductThroughButton({ activityServerId: selected.activityServerId, beeperId: store.$state.beeperId, hasLoading: true }));
  if (err) return;
  handleProdPayTypeOperation(res.data, state.selectAactivity!.buyWay, selected);
  state.show = false;
};

// 产品不同支付类型
const handleProdPayTypeOperation = (data: IGetBtnDefaultGoodsRes, buyWay: number, btnDetails: IObtainActivityButtonListRes) => {
  const { goods } = data;
  const currentTime = new Date();
  const startTime = new Date(btnDetails.buyBeginDate);
  const endTime = new Date(btnDetails.buyEndDate);
  if (currentTime <= startTime && currentTime >= endTime) {
    showToast('不在产品可购买时间');
    return;
  }
  switch (buyWay) {
    case 11:
    case 12:
      if (goods.goodsType !== 15) {
        // 快捷下单
        navigate({ url: `/subcontract/home/freePayOrderPlc/index?data=${encodeURIComponent(JSON.stringify(data))}` });
      } else {
        //弹窗支付下单 - 补差价产品
        useControllerStore().$patch({ compPriceDiffPopupData: { data: data, eventId: store.$state.btnInformation!.eventId, linkUrl: '' } });
      }
      break;
    case 13:
      // 详情页下单
      navigate({ url: `/subcontract/home/productDetail/index?product=${encodeURIComponent(JSON.stringify(data.goods))}&hasHomePath=true&hasSku=${goods.goodsType === 2 || goods.variantState === 2 ? 'true' : 'false'}` });
      break;
    case 14:
      // 结算页下单
      navigate({ url: `/subcontract/home/submitOrder/index?products=${encodeURIComponent(JSON.stringify({ ...goods, nums: 1 }))}` });
      break;
  }
};

defineExpose({
  handleProdPayTypeOperation,
});
</script>

<template>
  <view class="c-pd">
    <view class="c-br bg-white mb-12px overflow-hidden" v-for="item in state.activityList" :key="item.activityId" @click="navigate({ url: `/subcontract/home/activityRegistration/ActivityDetails?data=${encodeURIComponent(JSON.stringify(item))}` })">
      <image class="h-130px w-full" :src="item.mainImage" mode="aspectFill" />
      <view class="bg-white px-12px py-8px">
        <view class="fw-bold">{{ item.activityName }}</view>
        <view class="c-text-12 c-text-color-grey mt-4px">{{ item.introduce }}</view>
        <view class="flex flex-wrap justify-end">
          <template v-if="item.activityType === 1">
            <van-button class="ml-8px" type="primary" size="small" @tap.stop="handleActivityProductClick(item)">{{ item.mainBtnName }}</van-button>
          </template>
        </view>
      </view>
    </view>
  </view>

  <van-popup position="bottom" round :show="state.show" @close="state.show = false">
    <view class="bg-white w-full">
      <van-picker show-toolbar value-key="btnName" :columns="state.columns" title="请选择产品" @cancel="state.show = false" @confirm="handleActivityProductConfirm($event.detail.value)" />
    </view>
  </van-popup>

  <!-- 补差价弹窗组件 -->
  <CompPriceDiffPopup />
</template>
